package com.spsy.orders.schedule;

import com.alibaba.fastjson2.JSON;
import com.spsy.orders.domain.Orders;
import com.spsy.orders.service.IOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author: liuzhiping
 * @date: 2025/2/9 20:05
 **/

@Component
public class ScheduledTasks {

    @Autowired
    private com.spsy.orders.service.IOrdersService ordersService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 每隔5秒执行一次

/*@Scheduled(fixedRate = 5000)
    public void taskWithFixedRate() {
        System.out.println("Fixed rate task - " + System.currentTimeMillis() / 1000);
    }*//*

    // 每隔10秒执行一次，延迟5秒后开始执行
    */
/*@Scheduled(fixedDelay = 10000, initialDelay = 5000)
    public void taskWithFixedDelay() {
        System.out.println("Fixed delay task - " + System.currentTimeMillis() / 1000);
    }*/


    // 使用Cron表达式，每分钟的第30秒执行
    /*@Scheduled(cron = "10 * * * * ?")
    public void taskWithCronExpression() {
        System.out.println("Cron task - " + System.currentTimeMillis() / 1000);

        System.out.println("初始化插入50条数据到数据库");

        for(int i=0;i<50;i++){
            Orders orders = Orders.builder()
                    .orderId(Long.valueOf("1000"+i))
                    .productId("2000"+i)
                    .orderStatus("1")
                    .paymentStatus("01")
                    .payAmount(BigDecimal.ZERO)
                    .userId(Long.valueOf("9000"+i))
                    .orderNumber("3000-"+i)
                    .payAmount(BigDecimal.ZERO)
                    .totalAmount(BigDecimal.ONE)
                    .build();
            orders.setCreateTime(new Date());
            orders.setUpdateTime(new Date());
            int insertCount = this.ordersService.insertOrders(orders);
            System.out.println("insertCount:"+insertCount);
        }
    }*/


    // 使用Cron表达式，每8分钟的第30秒执行
    /*@Scheduled(cron = "5 * * * * ?")
    public void taskWithCronExpression2() {
        *//*System.out.println("Cron task - " + System.currentTimeMillis() / 1000);*//*

        //1：加载一周的数据，求出金额最大10条记录
        List<Orders> topTenList = this.ordersService.selectOrdersTotalAmountTopTen();
        System.out.println(JSON.toJSONString(topTenList));
        //2：放到redis当中

        String key = "spsy:order:total:amount:top:ten";
        this.redisTemplate.opsForValue().set(key,JSON.toJSONString(topTenList));

        //构建redis map
        String mapKey = "spsy:order:total:amount:top:ten:map";
        for (Orders orders : topTenList){
            this.redisTemplate.opsForHash().put(mapKey,String.valueOf(orders.getOrderId()),JSON.toJSONString(orders));
        }

    }*/

}

